package com.pur.zsms.documentsmanage.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.pur.zsms.accountmanage.vo.AccountVo;
import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.documentsmanage.po.DomPo;
import com.pur.zsms.documentsmanage.service.IDomService;
import com.pur.zsms.documentsmanage.vo.DomVo;
import com.pur.zsms.foodmanage.food.po.FoodMaterPo;
import com.pur.zsms.foodmanage.food.service.IFoodService;
import com.pur.zsms.foodmanage.food.vo.FoodMaterVo;
import com.pur.zsms.foodmanage.food.vo.FoodVo;
import com.pur.zsms.matermanage.mater.service.IMaterService;
import com.pur.zsms.ordercustommanage.vo.ExcelVo;
import com.pur.zsms.ordercustommanage.vo.SelectFoodVo;
import com.pur.zsms.pmsnmanage.role.vo.RoleVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.vo.UserVo;
import com.pur.zsms.supplier.service.ISupplierService;

@Controller
@RequestMapping(value = "/dom")
public class DomControllor {

	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(DomControllor.class);

	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	@Resource(name = "domService")
	private IDomService domService;

	@Resource(name = "supplierService")
	private ISupplierService supplierService;

	@RequestMapping(value = "/findDom.do", method = { RequestMethod.POST })
	@ResponseBody
	public String findDom(String id) {
		JSONObject json = new JSONObject();
		String a = "";
		try {

			if (id != null && !id.equals("")) {
				a = domService.getDomMenu(Integer.valueOf(id));
			} else {
				a = "[{ \"id\":1, \"text\":\"目录\" ,\"state\":\"closed\",\"folder\":\"1\"}] ";
			}

		} catch (GenericException e) {
			e.printStackTrace();
		}
		return a;
		// return json.toString();
	}

	// 下载
	@RequestMapping(value = "/downDom.do", method = { RequestMethod.POST })
	public void downDom(HttpServletRequest request, HttpServletResponse response, HttpSession session1, int id) {

		OutputStream toClient = null;

		try {
			// String link = domService.getLinkById(id);
			DomPo tDomPo = domService.getDomPoById(id);

			String realPath = session1.getServletContext().getRealPath("/");
			String filePath = realPath + File.separator + "jsp" + File.separator + "file" + File.separator;

			InputStream fis = new BufferedInputStream(new FileInputStream(filePath + tDomPo.getDomText()));

			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			// response.addHeader("Content-Disposition", "attachment;filename="
			// + new String(filename.getBytes()));

			response.setContentType("octets/stream");
			response.addHeader("Content-Type", "text/html; charset=utf-8");
			String downLoadName = new String(tDomPo.getDomText().getBytes("gbk"), "iso8859-1");
			response.addHeader("Content-Disposition", "attachment;filename=" + downLoadName);

			toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(buffer);

		} catch (UnsupportedEncodingException e1) {
		} catch (Exception e) {
		} finally {
			try {
				toClient.flush();
				toClient.close();
			} catch (IOException e) {
			}
		}
	}

	// 创建文件夹
	@RequestMapping(value = "/createFolder.do", method = { RequestMethod.POST })
	@ResponseBody
	public String createFolder(DomVo domVo) {
		JSONObject json = new JSONObject();
		boolean flag = true;
		try {
			flag = domService.addDomPo(domVo);
			if (flag) {
				json.put("success", true);
			} else {
				json.put("msg", domService.getMsg());
				json.put("success", false);
			}

		} catch (GenericException e) {
			e.printStackTrace();
		}
		return json.toString();
	}

	// 删除文件
	@RequestMapping(value = "/deleteDom.do", method = { RequestMethod.POST })
	@ResponseBody
	public String deleteDom(DomVo domVo) {
		JSONObject json = new JSONObject();
		try {
			boolean flag = domService.deleteDomPo(domVo);
			if (flag) {
				json.put("success", true);
			} else {
				json.put("msg", domService.getMsg());
				json.put("success", false);
			}
		} catch (GenericException e) {
			e.printStackTrace();
		}
		return json.toString();
	}

	@RequestMapping(value = "/uploadDomForSup.do", method = { RequestMethod.POST })
	@ResponseBody
	public String uploadDomForSup(DomVo domVo, HttpSession session1, HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws Exception {

		JSONObject json1 = new JSONObject();
		MultipartFile file = domVo.getFile();
		String temp = session.getServletContext().getRealPath(File.separator) + "temp"; // 临时目录
		File tempFile = new File(temp);
		if (!tempFile.exists()) {
			tempFile.mkdirs();
		}

		// 开始读取上传信息
		// int index = 0;
		if (file == null)
			return null;
		if (file.getSize() > 10000000) {
			throw new Exception("上传失败：文件大小不能超过10M");
		}
		String filename1 = file.getOriginalFilename();
		domVo.setDomText(filename1);
		// 校验文件夹目录
		boolean folderFlag = domService.checkFolder(domVo);
		if (folderFlag) {
			json1.put("msg", domService.getMsg());
			json1.put("success", false);
			return json1.toString();
		}
		// 校验文件名称是否存在相同
		boolean flag = domService.checkFolder(domVo);
		if (flag) {
			json1.put("msg", domService.getMsg());
			json1.put("success", false);
			return json1.toString();
		}

		String realPath = session1.getServletContext().getRealPath("/");
		String filePath = realPath + File.separator + "jsp" + File.separator + "templet" + File.separator + "excelSupperLookPrint";
		if (file.getSize() > 0) {
			try {
				saveFileFromInputStream(file.getInputStream(), filePath, filename1);
			} catch (IOException e) {
				System.out.println(e.getMessage());
				return null;
			}
		} else {
			throw new Exception("上传失败：上传文件不能为空");
		}

		// well, let's do nothing with the bean for now and return:
		domVo.setDomText(filename1);
		String link = "/home/context/" + filename1.toString();

		domVo.setDomLink(link);

		// 取得供货商id
		UserPo userInfo = (UserPo) session.getAttribute("user");
		int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
		domVo.setSupId(supId);
		domService.addDomPoForContext(domVo);

		json1.put("success", true);
		return json1.toString();
	}

	@RequestMapping(value = "/uploadDom.do", method = { RequestMethod.POST })
	@ResponseBody
	public String uploadDom(DomVo domVo, HttpSession session1, HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws Exception {

		JSONObject json1 = new JSONObject();
		MultipartFile file = domVo.getFile();
		String temp = session.getServletContext().getRealPath(File.separator) + "temp"; // 临时目录
		File tempFile = new File(temp);
		if (!tempFile.exists()) {
			tempFile.mkdirs();
		}

		// 开始读取上传信息
		// int index = 0;
		if (file == null)
			return null;
		if (file.getSize() > 10000000) {
			throw new Exception("上传失败：文件大小不能超过10M");
		}
		String filename1 = file.getOriginalFilename();
		domVo.setDomText(filename1);
		boolean flag = domService.checkFolder(domVo);
		if (flag) {
			json1.put("msg", domService.getMsg());
			json1.put("success", false);
			return json1.toString();
		}

		String realPath = session1.getServletContext().getRealPath("/");
		String filePath = realPath + "jsp" + File.separator + "file";

		if (file.getSize() > 0) {
			try {
				saveFileFromInputStream(file.getInputStream(), filePath, filename1);
			} catch (IOException e) {
				System.out.println(e.getMessage());
				return null;
			}
		} else {
			throw new Exception("上传失败：上传文件不能为空");
		}

		// well, let's do nothing with the bean for now and return:
		domVo.setDomText(filename1);
		String link = filePath + File.separator + filename1.toString();

		domVo.setDomLink(link);
		domService.addDomPoForContext(domVo);

		json1.put("success", true);
		return json1.toString();
	}

	public void saveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
		FileOutputStream fs = new FileOutputStream(path + File.separator + filename);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
	}

}
